package com.example.recording;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;

import com.example.recording.mixer.bean.AudioMsg;
import com.example.recording.mixer.service.AudioTaskCreator;
import com.example.recording.mixer.utils.FileUtils;
import com.example.recording.recorder.AudioFileUtils;
import com.example.recording.recorder.AudioRecorder;
import com.example.recording.sineaudio.AudioTrackManager;
import com.example.recording.widget.AntiAudioWaveSurfaceView;
import com.example.recording.widget.TimerView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity implements TimerView.OnTimerListener {
    private static final String TAG = "MainActivity";
    private static final int REQUEST_AUDIO_CODE = 1;

    private TimerView timerView;
    private ImageButton ibMicBtn;
    private AudioRecorder audioRecorder;
    // 定义播放声音的MediaPlayer
    private MediaPlayer mPlayer;
    private AntiAudioWaveSurfaceView antiAudioWave;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        timerView = findViewById(R.id.loading_view);
        ibMicBtn = findViewById(R.id.ib_mic);
        antiAudioWave = findViewById(R.id.visualizer_view);
        ibMicBtn.setOnTouchListener((View view, MotionEvent motionEvent) -> {
            switch (motionEvent.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    timerView.clean();
                    timerView.start();
                    break;
                case MotionEvent.ACTION_UP:
                    ibMicBtn.performClick();
                case MotionEvent.ACTION_CANCEL:
                    timerView.stop();
                    break;
            }
            return false;
        });
        timerView.setOnTimerListener(this);
        audioRecorder = AudioRecorder.getInstance();
      /*  // 创建MediaPlayer对象
        mPlayer = MediaPlayer.create(this, R.raw.beautiful);
        // 开发播放音乐
        mPlayer.start();*/
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (isFinishing() && mPlayer != null) {
            // 释放所有对象
            mPlayer.release();
            mPlayer = null;
        }
    }

    @Override
    public void onStartTimer(long startTime) {
        Log.e(TAG, "onStartTimer: ");
        //初始化录音
        String fileName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
        audioRecorder.createDefaultAudio(fileName);
        audioRecorder.startRecord((data, begin, end) -> {
            short[] sa = new short[data.length / 2];
            ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(sa);
            antiAudioWave.putAudioData(sa);
        });
        //  setupVisualizer(sessionId);
        antiAudioWave.start();
    }

    @Override
    public void onStopTimer(long duration) {
        Log.e(TAG, "onStopTimer: ");
        audioRecorder.stopRecord();
        List<File> pcmFiles = AudioFileUtils.getPcmFiles();
        Log.e(TAG, "onStopTimer: " + pcmFiles.size());
        antiAudioWave.stop();
    }

    @Override
    public void onCleanTimer() {

    }

    //----------------------------------------------------------------------------------------------


    AudioTrackManager audio;
    boolean isPlaySound;
    Thread thread;

    private void playSineAudio() {
        audio = new AudioTrackManager();
        audio.start(400);
        thread = new Thread(() -> {
            while (isPlaySound) {
                audio.play();
            }
        });
        isPlaySound = true;
        thread.start();
    }

    private void stopSineAudio() {
        isPlaySound = false;
    }

    /**
     * 选取音频文件
     */
    private void pickAudioFile() {

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("audio/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, REQUEST_AUDIO_CODE);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_AUDIO_CODE) {
                String path = FileUtils.queryFilePath(this, data.getData());
                Log.e(TAG, "选中文件路径 " + path);
            }
        }
    }

    /**
     * 合成音频
     */
    private void mixAudio(String path1, String path2) {

        if (TextUtils.isEmpty(path1) || TextUtils.isEmpty(path2)) {
            Log.e(TAG, "音频路径为空");
            return;
        }

        AudioTaskCreator.createMixAudioTask(this, path1, path2, 0.5f, 0.5f);
    }

    //音频处理后的回调
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveAudioMsg(AudioMsg msg) {
        if (msg != null && !TextUtils.isEmpty(msg.msg)) {
            String 处理后消息 = msg.msg;
            if (msg.path != null) {
                String 处理后音频路径 = msg.path;
            }
        }
    }

    private void playAudio(String path) {
        try {
            Intent it = new Intent(Intent.ACTION_VIEW);
            it.setDataAndType(Uri.parse("file://" + path), "audio/*");
            startActivity(it);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
